/**
 * 
 */
package com.csjbot.zfb;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;

/**
 * @author 作者：Zhangyangyang
 * @version 创建时间：2017年4月6日 上午10:33:46 类说明
 */
public class AlipayServicePort {
	private static String APP_ID = AlipayConfig.APPID;
	private static String APP_PRIVATE_KEY = AlipayConfig.RSA_PRIVATE_KEY;
	private static String CHARSET = AlipayConfig.CHARSET;
	private static String ALIPAY_PUBLIC_KEY = AlipayConfig.ALIPAY_PUBLIC_KEY;

	// 订单生成
	public static String addOrder(JSONObject json) throws AlipayApiException, UnsupportedEncodingException {
		String out_trade_no = json.getString("out_trade_no");
		// 订单名称，必填
		String subject = json.getString("subject");
		// 付款金额，必填
		String total_amount = json.getString("total_amount");
		// 商品描述，可空
		String body = json.getString("body");
		// 超时时间 可空
		String timeout_express = "50m";
		// 销售产品码 必填
		String product_code = "QUICK_WAP_PAY";
		/**********************/
		// SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
		// 调用RSA签名方式
		AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
				AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,
				AlipayConfig.SIGNTYPE);

		AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

		// 封装请求支付信息
		AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
		model.setOutTradeNo(out_trade_no);
		model.setSubject(subject);
		model.setTotalAmount(total_amount);
		model.setBody(body);
		model.setTimeoutExpress(timeout_express);
		model.setProductCode(product_code);
		alipay_request.setBizModel(model);
		// 设置异步通知地址
		alipay_request.setNotifyUrl(AlipayConfig.notify_url);
		// 设置同步地址
		alipay_request.setReturnUrl(AlipayConfig.return_url);
		AlipayTradeWapPayResponse response = null;
		try {
			response = client.sdkExecute(alipay_request);// 通过alipayClient调用API，获得对应的response类
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return AlipayConfig.URL + "?" + response.getBody();
	}

	// 查询订单
	public static JSONObject showOrderInfo(JSONObject json) throws AlipayApiException {
		JSONObject result = new JSONObject();
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID,
				APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2"); // 获得初始化的AlipayClient
		AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();// 创建API对应的request类
		request.setBizContent(json.toString());// 设置业务参数
		AlipayTradeQueryResponse response = alipayClient.execute(request);// 通过alipayClient调用API，获得对应的response类
		result = JSONObject.parseObject(response.getBody());
		// 根据response中的结果继续业务逻辑处理
		return result;
	}

	// 查询订单下载地址
	public static String showOrderDownUrl(JSONObject bill_json) throws AlipayApiException {
		String result = "";
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID,
				APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2"); // 获得初始化的AlipayClient
		AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();// 创建API对应的request类
		request.setBizContent(bill_json.toString());// 设置业务参数
		AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
		JSONObject json = JSONObject.parseObject(response.getBody());
		result = json.getJSONObject("alipay_data_dataservice_bill_downloadurl_query_response")
				.getString("bill_download_url");
		return result;

	}

	// 下载账单
	public static String downOrder(String time) throws AlipayApiException {
		JSONObject json = new JSONObject();
		json.put("bill_type", "trade");
		json.put("bill_date", time);
		String filePath = "D://20170406.zip";
		String fileUrl = showOrderDownUrl(json);
		if (fileUrl != null && fileUrl != "") {
			URL url = null;
			HttpURLConnection httpUrlConnection = null;
			InputStream fis = null;
			FileOutputStream fos = null;
			try {
				url = new URL(fileUrl);
				httpUrlConnection = (HttpURLConnection) url.openConnection();
				httpUrlConnection.setConnectTimeout(5 * 1000);
				httpUrlConnection.setDoInput(true);
				httpUrlConnection.setDoOutput(true);
				httpUrlConnection.setUseCaches(false);
				httpUrlConnection.setRequestMethod("GET");
				httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
				httpUrlConnection.connect();
				fis = httpUrlConnection.getInputStream();
				byte[] temp = new byte[1024];
				int b;
				fos = new FileOutputStream(new File(filePath));
				while ((b = fis.read(temp)) != -1) {
					fos.write(temp, 0, b);
					fos.flush();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (fis != null)
						fis.close();
					if (fos != null)
						fos.close();
					if (httpUrlConnection != null)
						httpUrlConnection.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return filePath;
	}

	// 交易关闭接口
	public static JSONObject dealClose(JSONObject json) throws AlipayApiException {
		JSONObject result = new JSONObject();
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "app_id",
				"your private_key", "json", "GBK", "alipay_public_key", "RSA2");
		AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
		request.setBizContent("{" + "    \"trade_no\":\"2013112611001004680073956707\","
				+ "    \"out_trade_no\":\"HZ0120131127001\"," + "    \"operator_id\":\"YX01\"" + "  }");
		AlipayTradeCloseResponse response = alipayClient.execute(request);
		if (response.isSuccess()) {
			System.out.println("调用成功");
		} else {
			System.out.println("调用失败");
		}
		return result;
	}

	// 退款接口
	public static JSONObject refund(JSONObject json) throws AlipayApiException {
		JSONObject result = new JSONObject();
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		request.setBizContent("{" +
		"    \"out_trade_no\":\"20150320010101001\"," +
		"    \"trade_no\":\"2014112611001004680073956707\"," +
		"    \"refund_amount\":200.12," +
		"    \"refund_reason\":\"正常退款\"," +
		"    \"out_request_no\":\"HZ01RF001\"," +
		"    \"operator_id\":\"OP001\"," +
		"    \"store_id\":\"NJ_S_001\"," +
		"    \"terminal_id\":\"NJ_T_001\"" +
		"  }");
		AlipayTradeRefundResponse response = alipayClient.execute(request);
		if(response.isSuccess()){
		System.out.println("调用成功");
		} else {
		System.out.println("调用失败");
		}
		return result;
	}

	// 查询退款接口
	public static JSONObject showRefund(JSONObject json) throws AlipayApiException {
		JSONObject result = new JSONObject();
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
		AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
		request.setBizContent("{" +
		"    \"trade_no\":\"20150320010101001\"," +
		"    \"out_trade_no\":\"2014112611001004680073956707\"," +
		"    \"out_request_no\":\"2014112611001004680073956707\"" +
		"  }");
		AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
		if(response.isSuccess()){
		System.out.println("调用成功");
		} else {
		System.out.println("调用失败");
		}
		return result;
	}

	public static void main(String[] args) throws UnsupportedEncodingException, AlipayApiException {

		
	}

}
